import requests
import json

my_key = "sk-b9f648c06fff48ae86a07e69c1fb51e8"
base_url = "https://api.deepseek.com"

headers = {
    'Authorization': f'Bearer {my_key}',
    'Content-Type': 'application/json',
}

def send_request(user_input):
    
    # 设置请求参数
    data = {
        "model": "deepseek-chat",
        "messages": [
            {"role": "system", "content": user_input},
            {"role": "user", "content": ""},
        ],
        "stream": True
    }
    
    #发送POST请求
    response = requests.post(f'{base_url}/chat/completions', headers = headers, json = data, stream = True)
    
    #检查响应状态码
    if response.status_code == 200:
        for line in response.iter_lines():
            if line:
                decoded_line = line.decode('utf-8')
                if decoded_line.startswith("data:"):
                    try:
                        json_data = json.loads(decoded_line[5:])
                        content = json_data['choices'][0]['delta'].get('content', '')
                        if content:
                            print(content, end='', flush=True)
                    except json.JSONDecodeError:
                        pass
        print()  # 换行
    else:
        print(f'请求失败，状态码:{response.status_code}')
        print(f'响应内容: {response.text}')

def get_model_list():
    response = requests.get(f'{base_url}/models', headers = headers)
    if response.status_code == 200:
        print(response.text)
    else:
        print(f'请求失败，状态码:{response.status_code}')
        print(f'响应内容: {response.text}')
        
def get_balance():
    payload = {}
    response = requests.get(f'{base_url}/user/balance', headers = headers, data = payload)
    if response.status_code == 200:
        print(response.text)
    else:
        print(f'请求失败，状态码:{response.status_code}')
        print(f'响应内容: {response.text}')

if __name__=="__main__":
    
    print("Welcome to Deepseek chat ! \U0001F600")
    print("enter 'quit' to exit")
    
    while True:
        user_input = input("User: ")
        
        if user_input.lower() == 'quit':
            print("Goodbye! \U0001F600")
            break
        elif user_input.lower() == 'list':
            get_model_list()
            continue
        elif user_input == 'balance':
            get_balance()
            continue
    
        send_request(user_input)


